const fs = require("fs");
const path = require("path");
const template = require("art-template");
let user = {
    id: 1001,
    name: "张三",
    phone: 12345678987
};
let users = [
    {
        id: 1001, name: "小花", phone: "17898765432", flag: true
    },
    {
        id: 1002, name: "大庆", phone: "17898765432", flag: true
    },
    {
        id: 1003, name: "白云", phone: "17898765432", flag: true
    },
    {
        id: 1004, name: "阿花", phone: "17898765432", flag: false
    }
];

const visitPath = {
    user: path.join(__dirname, "../template/user.html"),
    list: path.join(__dirname, "../template/list.html"),
    list2: path.join(__dirname, "../template/list2.html")
};

const findUser = function () {
    // let buffer1 = fs.readFileSync("./template/user.html");

    //将以当前文件参考的相对路径转换为系统物理真实路径，保证任何位置调用都不会因为路径错误导致错误
    // let userPath=path.join(__dirname,"../template/user.html");
    // let buffer1 = fs.readFileSync(userPath);

    let buffer1 = fs.readFileSync(visitPath.user);
    let str1 = buffer1.toString();//string
    str1 = str1.replace("{{id}}", user.id);
    str1 = str1.replace("{{name}}", user.name);
    str1 = str1.replace("{{phone}}", user.phone);
    return str1;
};

const findUsers = function () {
    // let userPath2=path.join(__dirname,"../template/user.html");
    let buffer11 = fs.readFileSync(visitPath.user);
    let str11 = buffer11.toString();//string

    let userStr = template.render(str11, user);
    return userStr;
};

const findList = function () {
    let buffer2 = fs.readFileSync(visitPath.list);
    let str2 = buffer2.toString();//string
    let strs = "";
    for (let i = 0; i < users.length; i++) {
        strs += `
            <tr>
                <td>${users[i].id}</td>
                <td>${users[i].name}</td>
                <td>${users[i].phone}</td>
                <td>${users[i].flag ? '是' : '否'}</td>
            </tr>
        `;
    }
    str2 = str2.replace("{{list}}", strs);
    return str2;
};

const findList2 = function () {
    let buffer4 = fs.readFileSync(visitPath.list2);
    let str4 = buffer4.toString();//string
    console.log(str4);
    let strs2 = template.render(str4, { userList: users });
    return strs2;
};
module.exports = {
    findUser,
    findUsers,
    findList,
    findList2
};